<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input placeholder="请输入充值方案名称" v-model="queryParam.search_key"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button style="margin-right: 8px" @click="resetQueryParams">重置</a-button>
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <span></span>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
          <a-button type="default" @click="onSetting" icon="setting">设置</a-button>
        </div>
      </div>

      <s-table rowKey="id" size="default" :columns="columns" :data="loadData" ref="table">
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该充值方案吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>
      <a-modal
        :title="isNew ? '创建充值方案' : '编辑充值方案'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        :bodyStyle="{ height: '600px', overflow: 'auto' }"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="充值名称" hasFeedback>
            <a-input
              placeholder="充值名称"
              v-decorator="['name', { rules: [{ required: true, message: '请填写充值名称' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="支付金额" extra="用户支付多少就充值多少">
            <a-input-number
              placeholder="支付金额"
              :formatter="(value) => `${value}元`"
              :parser="(value) => value.replace('元', '')"
              :min="0"
              :precision="2"
              :step="0.01"
              v-decorator="['pay_price', { initialValue: 0, rules: [{ required: true, message: '请填写充值金额' }] }]"
            />
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="赠送金额"
            extra="用户充值时，赠送的金额，默认为0"
          >
            <a-input-number
              placeholder="赠送金额"
              :formatter="(value) => `${value}元`"
              :parser="(value) => value.replace('元', '')"
              :min="0"
              :precision="2"
              :step="0.01"
              v-decorator="['send_price', { initialValue: 0 }]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="赠送积分"
            extra="用户充值时，赠送的积分，默认为0"
          >
            <a-input-number
              placeholder="赠送积分"
              :min="0"
              :precision="0"
              v-decorator="['send_integral', { initialValue: 0 }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序" extra="排序按降序排列">
            <a-input-number placeholder="排序" :min="0" v-decorator="['sort', { initialValue: 0 }]" />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 充值方案设置 -->
      <a-modal
        :title="'充值设置'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        :bodyStyle="{ height: '600px', overflow: 'auto' }"
        v-model="setting_visible"
        @ok="setting_handleOk"
      >
        <a-form class="permission-form" :form="setting_form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开启余额功能">
            <a-radio-group v-decorator="['recharge_wallet_status', { initialValue: 1 }]">
              <a-radio :value="0"> 关闭 </a-radio>
              <a-radio :value="1"> 开启 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="自定义金额"
            extra="用户可以自定义充值金额，但是不会有赠送"
          >
            <a-radio-group v-decorator="['recharge_custom_status', { initialValue: 1 }]">
              <a-radio :value="0"> 关闭 </a-radio>
              <a-radio :value="1"> 开启 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否开启余额抵扣">
            <a-radio-group v-decorator="['combine_pay', { initialValue: 1 }]">
              <a-radio :value="0"> 关闭 </a-radio>
              <a-radio :value="1"> 开启 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否开启余额转佣金">
            <a-radio-group v-decorator="['balance_to_commission', { initialValue: 1 }]">
              <a-radio :value="0"> 关闭 </a-radio>
              <a-radio :value="1"> 开启 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="余额赠送手续费比例">
            <a-input-number
              v-decorator="['give_balance_profit', { initialValue: 0 }]"
              :min="0"
              :precision="2"
            ></a-input-number>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="积分赠送手续费比例">
            <a-input-number
              v-decorator="['give_integral_profit', { initialValue: 0 }]"
              :min="0"
              :precision="2"
            ></a-input-number>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="佣金转余额手续费比例">
            <a-input-number
              v-decorator="['commission_to_balance', { initialValue: 0 }]"
              :min="0"
              :precision="2"
            ></a-input-number>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="积分转佣金手续费比例">
            <a-input-number
              v-decorator="['integral_to_commission', { initialValue: 0 }]"
              :min="0"
              :precision="2"
            ></a-input-number>
          </a-form-item>

        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import { rechargeList, rechargeDel, rechargeAdd, rechargeEdit, rechargeSetting } from '@/api/marketing'
import { link } from '@/api/diy'

const STATUS = {
  1: '显示',
  0: '不显示',
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '充值名称',
    dataIndex: 'name',
  },
  {
    title: '支付金额(元)',
    dataIndex: 'pay_price',
  },
  {
    title: '赠送金额(元)',
    dataIndex: 'send_price',
  },
  {
    title: '赠送积分',
    dataIndex: 'send_integral',
  },
  {
    title: '排序',
    dataIndex: 'sort',
  },
  {
    title: '添加时间',
    dataIndex: 'created_at',
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  name: 'ArticleList',
  components: {
    STable,
  },
  data() {
    return {
      rechargeInfo: {},
      LinkList: [],
      isNew: false,
      visible: false,
      setting_visible: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      form: this.$form.createForm(this),
      setting_form: this.$form.createForm(this),
      // 表头
      columns,
      modalLoading: false,
      statusSelectValue: {
        key: '1',
        label: '显示',
      },
      form_pic_url: '',
      form_ad_pic_url: '',
      form_p_pic_url: '',
      // 查询条件参数
      queryParam: {
        search_key: null,
      },
      recharge_setting: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return rechargeList(parameter)
          .then((res) => {
            this.recharge_setting = res.data.recharge_setting
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      let param = {}
      link(param).then((res) => {
        this.LinkList = res.data.list
      })
    },
    changeShow(item) {
      console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      rechargeEdit({
        key: item.id,
        is_show: item.is_show,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      this.form_pic_url = record.pic_url
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(record, ['id', 'name', 'pic_url', 'pay_price', 'send_price', 'send_integral', 'sort'])
        )
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        this.modalLoading = true
        if (this.isNew) {
          rechargeAdd(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('充值方案创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          rechargeEdit(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('充值方案编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    setting_handleOk(e) {
      e.preventDefault()
      this.setting_form.validateFields((err, values) => {
        if (err) {
          return false
        }

        this.modalLoading = true
        rechargeSetting({ ...this.rechargeInfo, ...values })
          .then((res) => {
            this.modalLoading = false
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success('充值方案编辑成功！')
              this.setting_visible = false
              this.$refs.table.refresh()
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.modalLoading = false
          })
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.form_pic_url = ''
    },
    onSetting() {
      this.setting_visible = true
      this.rechargeInfo = this.recharge_setting
      this.recharge_setting.recharge_wallet_status = parseInt(this.recharge_setting.recharge_wallet_status)
      this.recharge_setting.recharge_custom_status = parseInt(this.recharge_setting.recharge_custom_status)
      this.recharge_setting.combine_pay = this.recharge_setting.combine_pay
        ? parseInt(this.recharge_setting.combine_pay)
        : 1
      this.recharge_setting.balance_to_commission = this.recharge_setting.balance_to_commission
        ? parseInt(this.recharge_setting.balance_to_commission)
        : 1

      this.$nextTick(() => {
        this.setting_form.setFieldsValue(
          pick(this.recharge_setting, [
            'recharge_wallet_status',
            'recharge_custom_status',
            'combine_pay',
            'balance_to_commission',
            'give_balance_profit',
            'give_integral_profit',
            'commission_to_balance',
            'integral_to_commission'
          ])
        )
      })
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      rechargeDel({
        key: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('充值方案删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
      })
      this.$refs.table.refresh(true)
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
